package com.zsl.swing.redis.desktop.utils;

import com.alibaba.fastjson.JSON;
import com.zsl.swing.redis.desktop.common.Constants;
import com.zsl.swing.redis.desktop.model.NodeEntity;
import com.zsl.swing.redis.desktop.type.RedisTypeEnum;
import com.zsl.swing.redis.desktop.window.ZslRedisDesktopMainWindow;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.Protocol.Command;
import redis.clients.jedis.params.ScanParams;
import redis.clients.jedis.params.SetParams;
import redis.clients.jedis.resps.ScanResult;
import redis.clients.jedis.resps.Tuple;
import redis.clients.jedis.util.SafeEncoder;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 
 * @author 张帅令
 * &#064;description   与redis服务器交互入口
 *
 */
public class RedisUtils {
	private static final ConcurrentHashMap<String, NodeEntity> connectionMap = new ConcurrentHashMap<>(32);

	public static Map<String,String> infoKeyCount(NodeEntity entity){
		try (Jedis jedis = new Jedis(entity.getHost(), entity.getPort(),false)) {
			if(!StringUtils.isEmpty(entity.getPassword())){
				if(DEFAULT_USERNAME.equals(entity.getUsername())){
					jedis.auth(entity.getPassword());
				}else{
					jedis.auth(entity.getUsername(), entity.getPassword());
				}
			}

			String keyspace = jedis.info("Keyspace");
			StringTokenizer stringTokenizer = new StringTokenizer(keyspace, "\r\n");

			stringTokenizer.nextToken();
			Map<String,String> map = new HashMap<>();
			while(stringTokenizer.hasMoreElements()){
				String tk = stringTokenizer.nextToken();
				StringTokenizer dbTk = new StringTokenizer(tk, ",");
				String keyInfo = dbTk.nextToken();

				String[] split = keyInfo.split(":");
				map.put(split[0],split[1].replace("keys=", ""));

			}

			return map;
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return Collections.emptyMap();
		}
	}

	public static final String DEFAULT_USERNAME = "default";

	public static boolean testConn(NodeEntity entity) {
		try (Jedis jedis = new Jedis(entity.getHost(), entity.getPort(),false)) {

			String result;
			if(StringUtils.isEmpty(entity.getPassword())){
				result = jedis.ping(Constants.OK);
			}else{
				if(DEFAULT_USERNAME.equals(entity.getUsername())){
					result = jedis.auth(entity.getPassword());
				}else{
					result = jedis.auth(entity.getUsername(), entity.getPassword());
				}
			}

			System.out.println("结果:" + result);

			return Constants.OK.equalsIgnoreCase(result);
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}
	}
	
	public static boolean connect(String uniqueId) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			return jedis.isConnected();
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
	}
	
	public static int dbCount(String uniqueId) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			List<String> databases = jedis.configGet("databases");
			int dbCount = Integer.parseInt(databases.get(1));
			return Math.min(dbCount,Constants.MAX_DB_COUNT);
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return Constants.DB_COUNT;
		}finally {
			close(jedis);
		}
	}

	public static String type(String uniqueId,int dbIndex, String key){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);

			return jedis.type(key);
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return null;
		}finally {
			close(jedis);
		}
	}
	
	private static void close(Jedis jedis) {
		if(jedis != null) {
			jedis.close();
		}
	}
	
	private static Jedis buildJedis(String uniqueId) {
		NodeEntity entity = connectionMap.get(uniqueId);
		return buildJedis(entity);

	}

	private static Jedis buildJedis(NodeEntity entity){
		Jedis jedis = new Jedis(entity.getHost(), entity.getPort());

		jedis.getClient().setSoTimeout(30000);

		if(!StringUtils.isEmpty(entity.getPassword())) {
			if(DEFAULT_USERNAME.equals(entity.getUsername())){
				jedis.auth(entity.getPassword());
			}else{
				jedis.auth(entity.getUsername(), entity.getPassword());
			}
		}

		jedis.connect();
		return jedis;
	}
	
	public static void putConnectionMap(NodeEntity connectionEntity) {
		connectionMap.put(connectionEntity.getUniqueId(), connectionEntity);
	}
	
	public static void main(String[] args) {
		String host = "r-2zeruvuesgw2cciozcpd.redis.rds.aliyuncs.com";
		String pass = "M16B$cMF1XNP";
		
		NodeEntity entity = new NodeEntity("测试一下");
		entity.setUniqueId(UniqueIdUtils.getUniqueId());
		entity.setHost(host);
		entity.setPassword(pass);
		boolean resultString = testConn(entity);
		System.out.println(resultString);
	}

	public static void addConnections(List<NodeEntity> connections) {
		if(!CollectionUtils.isEmpty(connections)) {
			Map<String, NodeEntity> map = connections.stream().collect(Collectors.toMap(NodeEntity::getUniqueId, obj -> obj,(old, now) -> now));
			connectionMap.putAll(map);
		}
	}

	public static void removeConnection(String uniqueId) {
		connectionMap.remove(uniqueId);
	}

	public static boolean selectDb(String uniqueId, int dbIndex) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			return true;
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
		
	}

	public static ScanResult<String> scanDb(String uniqueId, int dbIndex, String key, String cursor,int scanCount) {
		Jedis jedis = null;
		try {

			String pattern = StringUtils.isEmpty(key)? Constants.REDIS_ALL_PATTERN: "*" + key.trim() + "*";
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			cursor = StringUtils.isEmpty(cursor)? ScanParams.SCAN_POINTER_START:cursor;
			ScanParams params = new ScanParams();
			params.match(pattern);

			params.count(scanCount);


			return jedis.scan(cursor,params);
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return null;
		}finally {
			close(jedis);
		}
	}

	public static ScanResult<String> scanResult(String uniqueId, int dbIndex, String key, String cursor,int scanCount) {
		Jedis jedis = null;
		try {

			String pattern = StringUtils.isEmpty(key)? Constants.REDIS_ALL_PATTERN: "*" + key.trim() + "*";
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			cursor = StringUtils.isEmpty(cursor)? ScanParams.SCAN_POINTER_START:cursor;
			ScanParams params = new ScanParams();
			params.match(pattern);

			params.count(scanCount);

			ScanResult<String> scanResult = jedis.scan(cursor, params);
			ZslRedisDesktopMainWindow.getZslLogPanel().log("scan cursor: " + cursor);

			while(true){
				List<String> resultList = scanResult.getResult();
				if(!CollectionUtils.isEmpty(resultList)){
					break;
				}

				String nextCursor = scanResult.getCursor();
				if(ScanParams.SCAN_POINTER_START.equals(nextCursor)){
					break;
				}

				ZslRedisDesktopMainWindow.getZslLogPanel().log("scan cursor: " + nextCursor);

//				try{
//					Thread.sleep(100L);
//				}catch (Exception e){
//					//ignore
//				}
				scanResult = jedis.scan(nextCursor, params);
			}

			return scanResult;
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return null;
		}finally {
			close(jedis);
		}
	}
	
	public static String get(String uniqueId,int dbIndex,String key) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
				jedis.select(dbIndex);
			String type = jedis.type(key);
			switch (type) {
			case "string":
				return jedis.get(key);
			case "list":
				return JSON.toJSONString(jedis.lrange(key, 0L, 1000L));
			case "set":
				return JSON.toJSONString(jedis.smembers(key));
			case "zset":
				List<Tuple> tuples = jedis.zrangeWithScores(key, 0L, 1000L);

				Map<String,Double> map = new HashMap<>();
				for(Tuple tuple:tuples){
					map.put(tuple.getElement(), tuple.getScore());
				}

				return JSON.toJSONString(map);
			case "hash":
				return JSON.toJSONString(jedis.hgetAll(key));
			default:
				return null;
			}
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return null;
		}finally {
			close(jedis);
		}
	}

	public static boolean setString(String uniqueId, int dbIndex, String key, String value, Long expireSeconds){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);

			SetParams params = new SetParams();
			if(!Objects.isNull(expireSeconds)){
				params.ex(expireSeconds.intValue());
			}
			String result = jedis.set(key, value, params);
			return Constants.OK.equalsIgnoreCase(result);
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
	}

	public static boolean setHash(String uniqueId, int dbIndex, String key, Map<String,String> valueMap){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);

			long result = jedis.hset(key, valueMap);
			return result > 0L;
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
	}

	public static boolean setList(String uniqueId, int dbIndex, String key, String[] values){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);

			long result = jedis.lpush(key, values);
			return result > 0L;
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
	}

	public static boolean setSet(String uniqueId, int dbIndex, String key, String[] values){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);

			long result = jedis.sadd(key, values);
			return result > 0L;
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
	}

	public static boolean setZSet(String uniqueId, int dbIndex, String key, Map<String,Double> values){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);

			long result = jedis.zadd(key, values);
			return result > 0L;
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
	}



	/*public static boolean add(String uniqueId, int dbIndex, KeyValueEntity params){
		if(Objects.isNull(params) || !params.isOk()){
			ZslRedisDesktopMainWindow.getZslErrorLogPanel().logError("参数有误");
			return false;
		}

		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			switch (params.getType()) {
				case "string":
					SetParams other = new SetParams();
					other.ex((int)params.getExpire());
					String result = jedis.set(params.getKey(), params.getValue(), other);
					return Constants.OK.equalsIgnoreCase(result);
				case "list":
					String ltrim = jedis.ltrim(key, 1L, 0L);
					if(!Constants.OK.equalsIgnoreCase(ltrim)){
						ZslRedisDesktopMainWindow.getZslErrorLogPanel().logError("删除原list失败");
						return false;
					}

					String[] list = JSON.parseArray(value, String.class).stream().toArray(String[]::new);
					Long lpush = jedis.lpush(key, list);

					return lpush > 0L;
				case "set":
					Long del = jedis.del(key);
					if(del < 1L){
						ZslRedisDesktopMainWindow.getZslErrorLogPanel().logError("删除原set失败");
						return false;
					}

					String[] set = JSON.parseArray(value, String.class).stream().toArray(String[]::new);
					Long sadd = jedis.sadd(key, set);

					return sadd > 0L;
				case "zset":
					jedis.zadd
					Long zDel = jedis.del(key);
					if(zDel < 1L){
						ZslRedisDesktopMainWindow.getZslErrorLogPanel().logError("删除原set失败");
						return false;
					}

					String[] zSet = JSON.parseArray(value, String.class).stream().toArray(String[]::new);
					Long sadd = jedis.zadd(key, zSet);

					return sadd > 0L;
				case "hash":
					return JSON.toJSONString(jedis.hgetAll(key));
				default:
					ZslRedisDesktopMainWindow.getZslErrorLogPanel().logError("不支持的类型");
					return false;
			}

			return true;
		} catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslErrorLogPanel().logError(e);
			return false;
		}finally {
			close(jedis);
		}
	}*/
	
	public static Set<String> keys(String uniqueId) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			return jedis.keys(Constants.REDIS_ALL_PATTERN);
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return null;
		}finally {
			close(jedis);
		}
	}

	public static String[] keysMatch(String uniqueId,int dbIndex,String match){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			Set<String> keys = jedis.keys("*" + match + "*");
			if(!CollectionUtils.isEmpty(keys)){
				return keys.toArray(new String[0]);
			}
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
		} finally {
			close(jedis);
		}
		return new String[0];
	}

	@SuppressWarnings("all")
	public static boolean scanAndDel(String uniqueId, int dbIndex, String keyword, int scanCount){
		String cursor = ScanParams.SCAN_POINTER_START;
		ScanResult<String> scanResult;
		do{
			scanResult = scanDb(uniqueId,dbIndex,keyword,cursor,scanCount);
			List<String> keyList = scanResult.getResult();
			cursor = scanResult.getCursor();

			ZslRedisDesktopMainWindow.getZslLogPanel().log("当前页匹配到的key数量为：" + (keyList == null? 0: keyList.size()));
			if(!CollectionUtils.isEmpty(keyList)){
				for(String key: keyList){
					boolean del = del(uniqueId, dbIndex, key);
					ZslRedisDesktopMainWindow.getZslLogPanel().log("删除["+key+"]结果：" + del);
				}
			}

		}while (!ScanParams.SCAN_POINTER_START.equals(cursor));

		ZslRedisDesktopMainWindow.getZslLogPanel().log("删除*" + keyword +"*完成！");
		return true;

//		 scanResult = scanDb(uniqueId, dbIndex, keyword, cursor, scanCount);
//
//		Jedis jedis = null;
//		try {
//			jedis = buildJedis(uniqueId);
//			jedis.select(dbIndex);
//
//			sc
//			Set<String> keys = jedis.keys("*" + match + "*");
//			if(!CollectionUtils.isEmpty(keys)){
//				jedis.del(keys.stream().toArray(String[]::new));
//			}
//			return true;
//		}catch (Exception e) {
//			ZslRedisDesktopMainWindow.getZslErrorLogPanel().logError(e);
//			return false;
//		} finally {
//			close(jedis);
//		}
	}

	public static boolean delMatch(String uniqueId,int dbIndex, String match){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			Set<String> keys = jedis.keys("*" + match + "*");
			if(!CollectionUtils.isEmpty(keys)){
				jedis.del(keys.toArray(new String[0]));
			}
			return true;
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		} finally {
			close(jedis);
		}
	}

	public static int delContainsKeyword(String uniqueId,int dbIndex, String match){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			Set<String> keys = jedis.keys("*" + match + "*");
			if(!CollectionUtils.isEmpty(keys)){
				jedis.del(keys.toArray(new String[0]));
			}
			return keys.size();
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return -1;
		} finally {
			close(jedis);
		}
	}
	
	public static boolean del(String uniqueId,int dbIndex, String key) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			return jedis.del(key) == 1L;
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return false;
		} finally {
			close(jedis);
		}
	}

	public static void delKeys(String uniqueId,int dbIndex,String[] keys){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			jedis.del(keys);
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
		} finally {
			close(jedis);
		}
	}

	public static void flushDb(String uniqueId, int dbIndex) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			jedis.flushDB();
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
		}finally {
			close(jedis);
		}
	}

	public static boolean existsKey(String uniqueId, int dbIndex, String keyword) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			return jedis.exists(keyword);
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return true;
		}finally {
			close(jedis);
		}
	}

	public static long memoryUsageInByte(String uniqueId, int dbIndex, String key){
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			Long spaceInByte = jedis.memoryUsage(key);

			return spaceInByte == null? 0L: spaceInByte;
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return 0L;
		}finally {
			close(jedis);
		}
	}

	public static String execute(String commandName,List<String> params, String uniqueId, int dbIndex){
		Command command;

		try{
			command = Protocol.Command.valueOf(commandName.toUpperCase());
		}catch (IllegalArgumentException e){
			return String.format(Constants.UN_KNOW_COMMAND, commandName);
		}

		Jedis jedis = null;
		try {
			NodeEntity entity = connectionMap.get(uniqueId);
			jedis = buildJedis(entity);
			jedis.select(dbIndex);

			Object obj = jedis.sendCommand(command, params.toArray(new String[0]));
			return convertRedisResult(obj);
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return e.getMessage();
		}finally {
			close(jedis);
		}
	}

	private static String convertRedisResult(Object obj){
		if(Objects.isNull(obj)){
			return "";
		}

		if(obj instanceof byte[]){
			byte[] res = (byte[]) obj;
			return SafeEncoder.encode(res);
		}

		if(obj instanceof Long){
			return String.valueOf(obj);
		}

		if(obj instanceof List<?>){
			List<?> resList = (List<?>) obj;
			List<String> resultList = new ArrayList<>();
			for(Object o: resList){
				resultList.add(convertRedisResult(o));
			}

			return JSON.toJSONString(resultList);
		}

		if(obj instanceof Set<?>){
			Set<?> resList = (Set<?>) obj;
			List<String> resultList = new ArrayList<>();
			for(Object o: resList){
				resultList.add(convertRedisResult(o));
			}

			return JSON.toJSONString(resultList);
		}



		return String.valueOf(obj);

	}
	
//	public static String execute(String target,String uniqueId,int dbIndex) {
//		String[] split = target.split(" ");
//		Command command;
//
//		try{
//			command = Protocol.Command.valueOf(split[0].toUpperCase());
//		}catch (IllegalArgumentException e){
//			return CommandMsg.UN_KNOW_COMMAND;
//		}
//
//		List<String> list = new ArrayList<>(split.length);
//		for(int i=1;i<split.length;i++) {
//			if(!StringUtils.isEmpty(split[i])) {
//				list.add(split[i]);
//			}
//		}
//		Jedis jedis = null;
//		try {
//			NodeEntity entity = connectionMap.get(uniqueId);
//			jedis = buildJedis(entity);
//			jedis.select(dbIndex);
//			Connection client = jedis.getClient();
//			client.sendCommand(command, list.toArray(new String[list.size()]));
//
//			switch (command) {
//			case PING:
//				return list.isEmpty()?client.getStatusCodeReply():SafeEncoder.encode(client.getBinaryBulkReply());
//			case SPOP:
//			case SRANDMEMBER:
//				return list.size() == 1?SafeEncoder.encode(client.getBinaryBulkReply()):
//						(list.size() == 2?JSON.toJSONString(BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply())):CommandMsg.PARAM_NUM_ERROR);
//			case GET:
//			case RANDOMKEY:
//			case GETSET:
//			case SUBSTR:
//			case HGET:
//			case LINDEX:
//			case LPOP:
//			case RPOP:
//			case RPOPLPUSH:
//			case ECHO:
//			case BRPOPLPUSH:
//			case GETRANGE:
//			case DUMP:
//			case MEMORY:
//			case XADD:
//				byte[] reply = client.getBinaryBulkReply();
//				return CollectionUtils.isEmpty(reply)?null:SafeEncoder.encode(reply);
//			case QUIT:
//				String quitReturn = client.getStatusCodeReply();
//				client.disconnect();
//				return quitReturn;
//			case SELECT:
//				int index = Integer.parseInt(list.get(0));
//				String statusCodeReply = client.getStatusCodeReply();
//
//				if("OK".equalsIgnoreCase(statusCodeReply)) {
//					client.select(index);
//					RedisConsoleWindow.putDbIndex(index);
//				}
//				return statusCodeReply;
//			case SLOWLOG:
//				String keyword = list.get(0);
//				if(Keyword.GET.name().equalsIgnoreCase(keyword)) {
//					return JSON.toJSONString(Slowlog.from(client.getObjectMultiBulkReply()));
//				}else if(Keyword.RESET.name().equalsIgnoreCase(keyword)) {
//					return client.getBulkReply();
//				}else if(Keyword.LEN.name().equals(keyword)) {
//					return String.valueOf(client.getIntegerReply());
//				}else {
//					return CommandMsg.NOW_UN_SUPPORT;
//				}
//			case MGET:
//			case HMGET:
//			case HVALS:
//			case LRANGE:
//			case CONFIG:
//			case GEOHASH:
//			case XREAD:
//			case XREADGROUP:
//			case XRANGE:
//			case XREVRANGE:
//			case XPENDING:
//			case XCLAIM:
//				List<String> build = BuilderFactory.STRING_LIST.build(client.getBinaryMultiBulkReply());
//				return JSON.toJSONString(build);
//			case GEOPOS:
//				List<GeoCoordinate> coordinates = BuilderFactory.GEO_COORDINATE_LIST.build(client.getObjectMultiBulkReply());
//				return JSON.toJSONString(coordinates);
//			case GEORADIUS:
//			case GEORADIUS_RO:
//			case GEORADIUSBYMEMBER:
//			case GEORADIUSBYMEMBER_RO:
//				List<GeoRadiusResponse> radiusResponses = BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply());
//				return JSON.toJSONString(radiusResponses);
//			case BITFIELD:
//				return JSON.toJSONString(client.getIntegerMultiBulkReply());
//			case HGETALL:
//				List<String> flatHash = BuilderFactory.STRING_LIST.build(client.getBinaryMultiBulkReply());
//				Iterator<String> iterator = flatHash.iterator();
//
//				Map<String,String> map = new HashMap<>();
//				while(iterator.hasNext()) {
//					map.put(iterator.next(), iterator.next());
//				}
//
//				return JSON.toJSONString(map);
//			case INCRBYFLOAT:
//			case HINCRBYFLOAT:
//			case INFO:
//			case GEODIST:
//				return client.getBulkReply();
//			case SET:
//			case TYPE:
//			case RENAME:
//			case SWAPDB:
//			case SETEX:
//			case MSET:
//			case HMSET:
//			case LTRIM:
//			case LSET:
//			case WATCH:
//			case FLUSHDB:
//			case FLUSHALL:
//			case SAVE:
//			case BGSAVE:
//			case BGREWRITEAOF:
//			case SHUTDOWN:
//			case SLAVEOF:
////			case DEBUG:
//			case RESTORE:
//			case PSETEX:
//			case CLIENT:
//			case MIGRATE:
//			case PFMERGE:
//			case XGROUP:
//				return client.getStatusCodeReply();
//			case ZINCRBY:
//			case ZSCORE:
//				return BuilderFactory.STRING.build(client.getOne());
//			case ZREVRANGEBYLEX:
//				if(list.size() == 3) {
//					return String.valueOf(client.getIntegerReply());
//				}else if(list.size() == 5) {
//					Set<String> keySet = BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply());
//					return JSON.toJSONString(keySet);
//				}
//				return CommandMsg.PARAM_NUM_ERROR;
//			case KEYS:
//			case HKEYS:
//			case SMEMBERS:
//			case SINTER:
//			case SUNION:
//			case SDIFF:
//			case ZRANGE:
//			case ZREVRANGE:
//			case ZREVRANGEBYSCORE:
//			case ZRANGEBYLEX:
//				Set<String> keySet = BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply());
//				return JSON.toJSONString(keySet);
//			case EXISTS:
//			case DEL:
//			case UNLINK:
//			case RENAMENX:
//			case DBSIZE:
//			case EXPIRE:
//			case EXPIREAT:
//			case TTL:
//			case TOUCH:
//			case MOVE:
//			case SETNX:
//			case MSETNX:
//			case DECRBY:
//			case DECR:
//			case INCR:
//			case INCRBY:
//			case APPEND:
//			case HSET:
//			case HSETNX:
//			case HINCRBY:
//			case HEXISTS:
//			case HDEL:
//			case HLEN:
//			case RPUSH:
//			case LPUSH:
//			case LLEN:
//			case LREM:
//			case SADD:
//			case SREM:
//			case SMOVE:
//			case SCARD:
//			case SISMEMBER:
//			case SINTERSTORE:
//			case SUNIONSTORE:
//			case SDIFFSTORE:
//			case ZADD:
//			case ZREM:
//			case ZRANK:
//			case ZREVRANK:
//			case ZCARD:
//			case ZCOUNT:
//			case ZREMRANGEBYRANK:
//			case ZREMRANGEBYSCORE:
//			case ZUNIONSTORE:
//			case ZINTERSTORE:
//			case ZLEXCOUNT:
//			case ZREMRANGEBYLEX:
//			case STRLEN:
//			case LPUSHX:
//			case PERSIST:
//			case RPUSHX:
//			case LINSERT:
//			case SETBIT:
//			case GETBIT:
//			case SETRANGE:
//			case BITPOS:
//			case PUBLISH:
//			case PEXPIRE:
//			case PEXPIREAT:
//			case LASTSAVE:
//			case BITCOUNT:
//			case BITOP:
//			case PTTL:
//			case WAIT:
//			case PFADD:
//			case PFCOUNT:
//			case GEOADD:
//			case HSTRLEN:
//			case XLEN:
//			case XACK:
//			case XDEL:
//			case XTRIM:
//				return String.valueOf(client.getIntegerReply());
//			/*case SYNC:
//			case SUBSCRIBE:
//			case PSUBSCRIBE:
//				return CommandMsg.NOW_UN_SUPPORT;*/
//			case SCAN:
//			case SSCAN:
//				List<Object> result = client.getObjectMultiBulkReply();
//				byte[] newCursor = (byte[]) result.get(0);
//			    @SuppressWarnings("unchecked") List<byte[]> rawResults = (List<byte[]>) result.get(1);
//
//			    JSONObject jsonObject = new JSONObject(4);
//			    jsonObject.put("cursor",SafeEncoder.encode(newCursor));
//			    jsonObject.put("result", BuilderFactory.STRING_SET.build(rawResults));
//			    return jsonObject.toJSONString();
//			case HSCAN:
//			case ZSCAN:
//				List<Object> rlt = client.getObjectMultiBulkReply();
//				String cor = BuilderFactory.STRING.build(rlt.get(0));
//				List<String> rltList = BuilderFactory.STRING_LIST.build(rlt.get(1));
//
//				List<Map.Entry<String, String>> targetList = new ArrayList<Map.Entry<String,String>>(rltList.size());
//
//				Iterator<String> itor = rltList.iterator();
//				while(itor.hasNext()) {
//					targetList.add(new AbstractMap.SimpleEntry<>(itor.next(),itor.next()));
//				}
//
//				JSONObject object = new JSONObject();
//				object.put("cursor", cor);
//				object.put("result", targetList);
//				return object.toJSONString();
//			case SORT:
//			case BLPOP:
//			case BRPOP:
//			case ZRANGEBYSCORE:
//			case TIME:
//				return JSON.toJSONString(client.getMultiBulkReply());
//			default:
//				return CommandMsg.NOW_UN_SUPPORT;
//			}
//		}catch (Exception e) {
//			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
//			return e.getMessage();
//		}finally {
//			close(jedis);
//		}
//
//	}


	public static boolean expire(String uniqueId, int dbIndex, String key, int expireSeconds) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			long expire = jedis.expire(key, expireSeconds);
			return (int) expire > 0;
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return true;
		}finally {
			close(jedis);
		}
	}

	public static long len(String uniqueId, int dbIndex, String keyName, String type) {
		Jedis jedis = null;
		try {
			jedis = buildJedis(uniqueId);
			jedis.select(dbIndex);
			if(RedisTypeEnum.isString(type)){
				return jedis.strlen(keyName);
			}

			if(RedisTypeEnum.isList(type)){
				return  jedis.llen(type);
			}

			if(RedisTypeEnum.isSet(type)){
				return jedis.scard(keyName);
			}

			if(RedisTypeEnum.isZSet(type)){
				return jedis.zcard(keyName);
			}

			if(RedisTypeEnum.isHash(type)){
				return jedis.hlen(keyName);
			}

			return -1;
		}catch (Exception e) {
			ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
			return -1;
		}finally {
			close(jedis);
		}
	}
}
